#include "connectionmanager.h"

ConnectionManager::ConnectionManager(QObject *parent) :
    QObject(parent)
{

}

bool ConnectionManager::addConnection(int sockDescriptor)
{
    return createThread(sockDescriptor)!=0;
}

ConnectionThread *ConnectionManager::createThread(int sockDecriptor)
{
    ConnectionThread *pThread = 0;
    try
    {
        pThread = new ConnectionThread( sockDecriptor, this);
        connect(pThread, SIGNAL(finished()), this, SLOT(closeThread()));
        pThread->start();
        qDebug("begin thread: 0x%x", pThread);
    }
    catch(...)
    {
        qCritical("Error in file: %s, line: %d", __FILE__, __LINE__);
        if( pThread)
        {
            delete pThread;
            pThread = 0;
        }
    }

    return pThread;
}

void ConnectionManager::closeThread()
{
    if(ConnectionThread *pThread = qobject_cast<ConnectionThread *>(sender()))
    {
        qDebug("end thread: 0x%x", pThread);
        pThread->deleteLater();
    }
}

